<template>
  <div class="page-container">
    <div class="page-header">
      <h2>数据分析</h2>
    </div>

    <!-- 数据概览 -->
    <div class="data-overview">
      <div class="overview-card">
        <div class="overview-icon">👨‍🎓</div>
        <div class="overview-content">
          <div class="overview-title">学生总数</div>
          <div class="overview-number">{{ statistics.totalStudents }}</div>
        </div>
      </div>
      <div class="overview-card">
        <div class="overview-icon">📚</div>
        <div class="overview-content">
          <div class="overview-title">任务总数</div>
          <div class="overview-number">{{ statistics.totalTasks }}</div>
        </div>
      </div>
      <div class="overview-card">
        <div class="overview-icon">✅</div>
        <div class="overview-content">
          <div class="overview-title">进行中任务</div>
          <div class="overview-number">{{ statistics.activeTasks }}</div>
        </div>
      </div>
      <div class="overview-card">
        <div class="overview-icon">📊</div>
        <div class="overview-content">
          <div class="overview-title">班级数</div>
          <div class="overview-number">{{ statistics.totalClasses }}</div>
        </div>
      </div>
    </div>

    <div class="charts-container">
      <!-- 学生统计 -->
      <div class="chart-card">
        <div class="chart-header">
          <h3>学生分布统计</h3>
          <div class="chart-actions">
            <select v-model="studentChartType" @change="updateStudentChart">
              <option value="gender">性别分布</option>
              <option value="grade">年级分布</option>
              <option value="status">状态分布</option>
            </select>
          </div>
        </div>
        <div class="chart-content" ref="studentChart"></div>
      </div>

      <!-- 任务统计 -->
      <div class="chart-card">
        <div class="chart-header">
          <h3>任务完成情况</h3>
          <div class="chart-actions">
            <select v-model="taskChartType" @change="updateTaskChart">
              <option value="status">任务状态</option>
              <option value="type">任务类型</option>
            </select>
          </div>
        </div>
        <div class="chart-content" ref="taskChart"></div>
      </div>
    </div>
  </div>
</template>

<script>
import { studentApi, taskApi } from '@/api'
import * as echarts from 'echarts'

export default {
  name: 'DataAnalysis',
  data() {
    return {
      students: [],
      tasks: [],
      studentChartType: 'gender',
      taskChartType: 'status',
      studentChart: null,
      taskChart: null,
      statistics: {
        totalStudents: 0,
        totalTasks: 0,
        activeTasks: 0,
        totalClasses: 4 // 固定值：初一、初二各两个班
      }
    }
  },
  async created() {
    await this.fetchData()
    this.initCharts()
    this.calculateStatistics()
  },
  mounted() {
    window.addEventListener('resize', this.handleResize)
  },
  beforeUnmount() {
    window.removeEventListener('resize', this.handleResize)
    this.disposeCharts()
  },
  methods: {
    async fetchData() {
      try {
        const [studentsRes, tasksRes] = await Promise.all([studentApi.getStudents(), taskApi.getTasks()])
        this.students = studentsRes.data
        this.tasks = tasksRes.data
      } catch (error) {
        console.error('获取数据失败:', error)
        this.$message.error('获取数据失败')
      }
    },
    calculateStatistics() {
      this.statistics.totalStudents = this.students.length
      this.statistics.totalTasks = this.tasks.length
      this.statistics.activeTasks = this.tasks.filter((task) => new Date(task.endTime) > new Date()).length
    },
    initCharts() {
      this.studentChart = echarts.init(this.$refs.studentChart)
      this.taskChart = echarts.init(this.$refs.taskChart)
      this.updateStudentChart()
      this.updateTaskChart()
    },
    updateStudentChart() {
      let data = []
      let title = ''

      switch (this.studentChartType) {
        case 'gender':
          data = this.getGenderDistribution()
          title = '学生性别分布'
          break
        case 'grade':
          data = this.getGradeDistribution()
          title = '学生年级分布'
          break
        case 'status':
          data = this.getStatusDistribution()
          title = '学生状态分布'
          break
      }

      const option = {
        title: {
          text: title,
          left: 'center'
        },
        tooltip: {
          trigger: 'item',
          formatter: '{b}: {c} ({d}%)'
        },
        legend: {
          orient: 'vertical',
          left: 'left'
        },
        series: [
          {
            type: 'pie',
            radius: '50%',
            data: data,
            emphasis: {
              itemStyle: {
                shadowBlur: 10,
                shadowOffsetX: 0,
                shadowColor: 'rgba(0, 0, 0, 0.5)'
              }
            }
          }
        ]
      }

      this.studentChart.setOption(option)
    },
    updateTaskChart() {
      let data = []
      let title = ''

      switch (this.taskChartType) {
        case 'status':
          data = this.getTaskStatusDistribution()
          title = '任务状态分布'
          break
        case 'type':
          data = this.getTaskTypeDistribution()
          title = '任务类型分布'
          break
      }

      const option = {
        title: {
          text: title,
          left: 'center'
        },
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'shadow'
          }
        },
        xAxis: {
          type: 'category',
          data: data.map((item) => item.name),
          axisLabel: {
            interval: 0,
            rotate: 30
          }
        },
        yAxis: {
          type: 'value'
        },
        series: [
          {
            data: data.map((item) => item.value),
            type: 'bar',
            barWidth: '40%',
            itemStyle: {
              color: function (params) {
                const colors = ['#409EFF', '#67C23A', '#E6A23C', '#F56C6C', '#909399']
                return colors[params.dataIndex % colors.length]
              }
            }
          }
        ]
      }

      this.taskChart.setOption(option)
    },
    getGenderDistribution() {
      const male = this.students.filter((s) => s.gender === 'male').length
      const female = this.students.filter((s) => s.gender === 'female').length
      return [
        { value: male, name: '男生' },
        { value: female, name: '女生' }
      ]
    },
    getGradeDistribution() {
      const gradeCount = {}
      this.students.forEach((student) => {
        gradeCount[student.grade] = (gradeCount[student.grade] || 0) + 1
      })
      return Object.entries(gradeCount).map(([grade, count]) => ({
        value: count,
        name: grade
      }))
    },
    getStatusDistribution() {
      const statusMap = {
        active: '在读',
        suspended: '休学',
        graduated: '毕业'
      }
      const statusCount = {}
      this.students.forEach((student) => {
        statusCount[student.status] = (statusCount[student.status] || 0) + 1
      })
      return Object.entries(statusCount).map(([status, count]) => ({
        value: count,
        name: statusMap[status] || status
      }))
    },
    getTaskStatusDistribution() {
      const now = new Date()
      const notStarted = this.tasks.filter((t) => new Date(t.startTime) > now).length
      const inProgress = this.tasks.filter((t) => new Date(t.startTime) <= now && new Date(t.endTime) > now).length
      const completed = this.tasks.filter((t) => new Date(t.endTime) <= now).length

      return [
        { value: notStarted, name: '未开始' },
        { value: inProgress, name: '进行中' },
        { value: completed, name: '已结束' }
      ]
    },
    getTaskTypeDistribution() {
      const typeMap = {
        vocabulary: '词汇练习',
        reading: '阅读理解',
        listening: '听力训练',
        speaking: '口语练习',
        writing: '写作任务'
      }
      const typeCount = {}
      this.tasks.forEach((task) => {
        typeCount[task.type] = (typeCount[task.type] || 0) + 1
      })
      return Object.entries(typeCount).map(([type, count]) => ({
        value: count,
        name: typeMap[type] || type
      }))
    },
    handleResize() {
      this.studentChart?.resize()
      this.taskChart?.resize()
    },
    disposeCharts() {
      this.studentChart?.dispose()
      this.taskChart?.dispose()
    }
  }
}
</script>

<style scoped>
.page-container {
  padding: 20px;
}

.page-header {
  margin-bottom: 24px;
}

.charts-container {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 24px;
  margin-bottom: 24px;
  margin-top: 40px;
}

.chart-card {
  background: white;
  border-radius: 8px;
  padding: 20px;
  border: 1px solid #dcdfe6;
}

.chart-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.chart-header h3 {
  margin: 0;
  font-size: 16px;
  color: #303133;
}

.chart-actions select {
  padding: 6px 12px;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  font-size: 14px;
  color: #606266;
}

.chart-content {
  height: 400px;
}

.data-overview {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  gap: 24px;
}

.overview-card {
  background: rgba(226, 223, 223, 0.616);
  border-radius: 8px;
  padding: 20px;
  display: flex;
  align-items: center;
  gap: 16px;
}

.overview-icon {
  font-size: 32px;
  color: #409eff;
}

.overview-content {
  flex: 1;
}

.overview-title {
  font-size: 14px;
  color: #909399;
  margin-bottom: 8px;
}

.overview-number {
  font-size: 24px;
  color: #303133;
  font-weight: 500;
}

@media (max-width: 1200px) {
  .charts-container {
    grid-template-columns: 1fr;
  }

  .data-overview {
    grid-template-columns: repeat(2, 1fr);
  }
}

@media (max-width: 768px) {
  .data-overview {
    grid-template-columns: 1fr;
  }
}
</style>
